import tkinter
from tkinter import *
import tkinter.filedialog
from op_scrapy import Op_scrapy
import time, threading
from tkinter import messagebox

class My_tk():
    def __init__(self, tk):
        self.op_scrapy = Op_scrapy()
        # 界面基本设置
        self.root = tk
        self.root.title("我的scrapy 爬虫")
        self.root.geometry("350x500")
        # 创建初始爬虫功能选择按钮
        self.choice_frame = Frame(self.root)
        self.choice_frame.pack()
        self.qcwy_button = Button(self.choice_frame, text='爬取前程无忧的招聘信息', command=self.show_qcwy)
        self.qcwy_button.pack()


    def show_qcwy(self):
        # 隐藏[选择] 界面，显示为爬取【获取京东】界面
        self.choice_frame.pack_forget()  # 隐藏选择 界面
        self.build_qcwy_frame()  # 创建【爬取京东】 界面

    def build_qcwy_frame(self):
        # 京东页面
        self.qcwy_frame = Frame(self.root, height=500, width=350)
        self.qcwy_frame.place(x=0, y=0)
        go_back_button = Button(self.qcwy_frame, text='返回', command=self.back)
        go_back_button.place(x=10, y=10)
        self.search_key_label = Label(self.qcwy_frame, text='搜索关键字:')
        self.search_key_label.place(x=10, y=50)
        self.search_key_word = Entry(self.qcwy_frame)
        self.search_key_word.place(x=100, y=50)
        self.search_key_word.insert(0, '剪辑')

        self.page_num_label = Label(self.qcwy_frame, text='爬取页数:')
        self.page_num_label.place(x=10, y=90)
        self.page_num_value = Entry(self.qcwy_frame)
        self.page_num_value.place(x=100, y=90)
        self.page_num_value.insert(0, '1')

        self.go_spider_button = Button(self.qcwy_frame, text='招聘信息数据',
                                       command=self.go_spider_qcwy)
        self.go_spider_button.place(x=30, y=140)

        self.go_qcwy_login = Button(self.qcwy_frame, text='浏览器已确认登录后，点击',
                                       command=self.update_qcwy_login_status)
        self.go_qcwy_login.place(x=30, y=190)

        self.spidering_info = Listbox(self.qcwy_frame, width=40)
        self.spidering_info.place(x=10, y=240)
        self.go_qcwy_login.config(state=tkinter.DISABLED)


    def go_spider_qcwy(self):
        if len(self.search_key_word.get()) == 0:
            messagebox.showerror('错误信息', '搜索关键字不能为空')
            return
        try:
            page_count = int(self.page_num_value.get())
            if page_count < 1:
                messagebox.showerror('错误信息', '爬取总页数不能小于1')
                return
        except:
            messagebox.showerror('错误信息', '爬取总页数必须为大于0的正整数')
            return

        self.spidering_info.insert('end', '开始爬虫')
        self.go_spider_button.config(state=tkinter.DISABLED)
        self.the_running_info = threading.Thread(target=self.show_running_info)
        self.the_running_info.start()
        params = [self.search_key_word.get(), page_count]
        op_result = self.op_scrapy.start('qcwy', params)
        self.go_qcwy_login.config(state=tkinter.NORMAL)
        if op_result == False:
            self.spidering_info.insert('end', '爬虫方案有误！！！')
        
    def update_qcwy_login_status(self):
        self.spidering_info.insert('end', '浏览器已确认登录，等scrapy响应')
        self.op_scrapy.parent_conn.send('login')
        self.go_qcwy_login.config(state=tkinter.DISABLED)

    def show_running_info(self):
        running = True
        time1 = int(time.time())
        self.spidering_info.insert('end', '爬虫线程启动')
        self.spidering_info.insert('end', "爬虫线程id:" + str(self.op_scrapy.spider_pid))
        self.spidering_info.insert('end', "Scrapy开始运行......")
        while running :
            now_time = int(time.time() - time1)
            if now_time % 2 == 0:
                if self.op_scrapy.spider_pid != 123456:
                    running = self.op_scrapy.check_scrapying()
            if self.op_scrapy.parent_conn.poll():
                info_scrapy = self.op_scrapy.parent_conn.recv()
                self.spidering_info.insert('end', info_scrapy)
        self.spidering_info.insert('end', '爬虫线程关闭')
        self.go_spider_button.config(state=tkinter.NORMAL)
        if 'qcwy_frame' in dir(self):
            self.go_qcwy_login.config(state=tkinter.DISABLED)


    def back(self):
        # 返回上一级选择界面，把关于诗句/简历 界面的信息、控件全部删除(ps:不然再进入时会有痕迹)
        if 'qcwy_frame' in dir(self):
            self.qcwy_frame.destroy()  # 删除京东界面(控件)
            delattr(self, 'qcwy_frame')  # 彻底删除属性
        self.choice_frame.pack()  # 显示最初始的选择界面
        print(self.op_scrapy.spider_pid)
        self.op_scrapy.stop_scrapy()  # 结束exe程序

